<template>
  <NDataTable :columns="columns" :data="orders"></NDataTable>
  <NPagination
    class="page"
    v-if="pagination.totalCount"
    v-model:page="pagination.page"
    v-model:page-size="pagination.pageSize"
    :page-count="pagination.totalCount"
    @update:page="pagination.onChange"
  />
</template>

<script lang="ts" setup>
import { reactive, h } from "vue";
import { NDataTable, NTag, NButton, NPagination, useMessage } from "naive-ui";

import { useOrders } from "@/hooks/Order";
import { useUserStore } from "@/stores/user";

const props = defineProps<{
  status: number;
}>();

const user = useUserStore();
const message = useMessage();

const orderStatus: any = {
  1: "待发货",
  2: "待收货",
  3: "已完成",
};
const { total, orders, getOrders } = useOrders();

const columns = [
  {
    title: "ID",
    key: "ID",
  },
  {
    title: "快递号",
    key: "TransportID",
  },
  {
    title: "状态",
    key: "Status",
    render(row: any) {
      let type: any = "info";
      switch (row.Status) {
        case 1:
          type = "info";
          break;
        case 2:
          type = "warning";
          break;
        case 3:
          type = "success";
          break;
      }
      return h(
        NTag,
        {
          type,
        },
        {
          default: () => orderStatus[row.Status],
        }
      );
    },
  },
  {
    title: "操作",
    key: "Options",
    render(row: any) {
      if (row.Status == 2) {
        return h(
          NButton,
          {
            type: "error",
            async onClick() {
              const msg = await user.finishOrder(row.ID);
              await getOrders({
                Status: props.status,
                Page: pagination.page,
                PageSize: pagination.pageSize,
              });
              pagination.totalCount = Math.ceil(
                total.value / pagination.pageSize
              );
              message.success(msg);
            },
          },
          {
            default() {
              return "收货";
            },
          }
        );
      }
      return "暂无操作";
    },
  },
];

const pagination = reactive({
  page: 1,
  pageSize: 5,
  totalCount: 0,
  onChange: async (page: number) => {
    await getOrders({
      Status: props.status,
      Page: page,
      PageSize: pagination.pageSize,
    });
  },
});

(async () => {
  await getOrders({
    Status: props.status,
    Page: pagination.page,
    PageSize: pagination.pageSize,
  });
  pagination.totalCount = Math.ceil(total.value / pagination.pageSize);
})();
</script>

<style lang="less" scoped>
.page {
  margin-top: 1.5em;
  display: flex;
  justify-content: center;
}
</style>
